<template>
  <el-form-item :prop="prop" :label="label">
    <el-button style="float: left; position: absolute; z-index: 10;" text @click="configRef.show()"
      v-if="selectId && loginInfo.userId == 1300000000101"></el-button>
    <el-popover placement="bottom-start" :width="popoverWidth" trigger="click" v-model:visible="showPopover"
      popper-class="popover-class" popper-style="padding: 10px 1px 5px 1px" :disabled="!isEdit" @show="show">
      <template #reference>
        <el-input v-bind="$attrs" :disabled="!isEdit" v-model="model" clearable @keydown="preventInput"
          @paste="preventInput" :style="inputStyle" />
      </template>
      <el-scrollbar max-height="35vh">
        <view v-for="row in list">
          <view v-if="row.canEdit">
            <el-input v-model="row.title" @click="doEdit(row)" :placeholder="row.title.length > 0 ? '' : '其他'"
              :class="row.isEdit ? 'edit' : 'not-edit'" size="medium">
              <template #prepend v-if="multi">
                <el-button :class="row.isEdit ? 'fa fa-check-circle' : 'fa fa-circle-o'" size="medium"
                  style="font-size: medium;" @click="changeSelect(row)" />
              </template>
              <template #append v-if="row.isEdit && !multi">
                <el-button class="fa fa-check" v-show="row.isEdit" @click="submitRow(row)" />
              </template>
            </el-input>
          </view>
          <view v-else>
            <el-input v-model:value="row.title" readonly @click="submitRow(row)" class="not-edit" size="medium">
              <template #prepend v-if="multi">
                <el-button :class="row.isEdit ? 'fa fa-check-circle' : 'fa fa-circle-o'" size="medium"
                  style="font-size: medium;" @click="changeSelect(row)" />
              </template>
            </el-input>
          </view>
        </view>
      </el-scrollbar>
      <div v-if="multi" style="display: flex; justify-content: flex-end; padding: 10px 30px;">
        <el-button type="info" @click="showPopover = false"> 取消 </el-button>
        <span style="width: 30px;"></span>
        <el-button type="primary" @click="submitMulti"> 确定 </el-button>
      </div>
    </el-popover>
  </el-form-item>
  <SelectItemConfig ref="configRef" :options="options" :selectId="selectId" @uploadOptions="uploadOptions">
  </SelectItemConfig>
</template>

<script lang="ts" setup>
/* 选项可以修改的下拉框, 使用:  title 为 '' 也支持(其他)
<MkSelectEdit label="孕产史" prop="yunChanShi" :isEdit="isEdit" v-model="model.yunChanShi"
  :options="[{ title: '无', canEdit: false, }, { title: '有 , 孕 x, 产 x', canEdit: true, }, { title: '', canEdit: true, }]">
</MkSelectEdit>
待定: 增加多选功能, 
待定: 新增过的其他选项缓存本地或服务器
-- 样式优化(去掉边框,去掉背景,增加鼠标经过事件,增加padding),
*/
import { getInputWidth } from './shared';
import { loginInfo } from '/@/stores/baseInfo/';
import SelectItemConfig from './SelectItemConfig4Edit.vue';

// 外部入参选项格式
export interface OptionType {
  title: string,
  canEdit: boolean, // 是否可以编辑
}

// 内部选项格式
interface ItemType {
  title: string,
  isEdit: boolean, // 是否编辑状态
  canEdit: boolean, // 是否可以编辑
}

defineOptions({
  name: 'MkSelectEdit'
})

const props = defineProps({
  prop: {
    type: String,
  },
  label: {
    type: String,
  },
  isEdit: {
    type: Boolean,
    default: true
  },
  append: { // 是否显示append
    type: Boolean,
    default: false
  },
  col: { // 控制宽度, 最多设置为3, 特殊情况可以设置为4
    type: Number,
    default: 1
  },
  selectId: {
    // 选择框的id, 用于缓存选项, 
    // 未设置selectId时, 不缓存选项, 
    // 如果两个MkSelect的selectId相同, 则会共享选项
    type: String,
  },
  multi: { // 是否多选, 默认单选
    type: Boolean,
    default: false
  },
  options: { // 默认选项
    type: Array<OptionType>,
    required: true,
  },
})

const model = defineModel<string>();
const configRef = ref(); // 用于编辑选项的表格
const { inputStyle } = getInputWidth(props.col);
const showPopover = ref(false)
const popoverWidth = ref(300);

const list = ref([] as ItemType[])

/** 显示选项时，根据输入框内容确定选项的勾选状态 */
const show = () => {
  if (!props.multi) {
    return;
  }
  if (model.value) {
    const modelList = model.value.split("，")
    list.value.forEach(item => {
      if (modelList.indexOf(item.title) > -1) {
        item.isEdit = true
      } else {
        item.isEdit = false
      }
    })
  } else {
    list.value.forEach(item => item.isEdit = false)
  }
}

// 点击编辑按钮, 切换编辑状态, 其他选项取消编辑状态
const doEdit = (row: ItemType) => {
  if (row.isEdit) {
    return;
  }

  var isEdit = row.isEdit;
  if (!props.multi) {
    // 如果单选, 把其他选项设置为非编辑状态
    list.value.forEach(item => {
      item.isEdit = false;
    });
  }
  row.isEdit = !isEdit;
}

// 点击提交按钮, 提交编辑内容, 其他选项取消编辑状态
const submitRow = (row: ItemType) => {
  if (props.multi) {
    changeSelect(row)
    return;
  }
  list.value.forEach(item => {
    item.isEdit = false;
  });
  row.isEdit = true;

  model.value = row.title;
  showPopover.value = false;
}

// 多选, 切换选中状态
const changeSelect = (row: ItemType) => {
  row.isEdit = !row.isEdit;
}

// 多选, 提交多选内容
const submitMulti = () => {
  let valList: string[] = []
  list.value.forEach(item => {
    if (item.isEdit && item.title) {
      valList.push(item.title)
    }
  });
  model.value = valList.join('，');
  showPopover.value = false;
}

/** 设置input框禁止输入 */
const preventInput = (e: Event) => {
  e.preventDefault();
}

// 更新选项
const uploadOptions = (options: any) => {
  let maxLength = 300;
  list.value = options.map(item => {
    maxLength = Math.max(maxLength, item.title.length * 13);
    return {
      title: item.title,
      isEdit: false,
      canEdit: item.canEdit,
    }
  })
  popoverWidth.value = maxLength;
}
</script>

<style lang='scss' scoped>
:deep(.el-input__inner) {
  cursor: pointer !important;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  box-shadow: 0 0 0 0 var(--el-disabled-border-color) inset !important;
}

:deep(.el-input-group__prepend) {
  background-color: #fff;
  box-shadow: 0 0 0 0 var(--el-input-border-color) inset,
    0 0 0 0 var(--el-input-border-color) inset,
    0 0 0 0 var(--el-input-border-color) inset
}

.edit {
  margin-bottom: 5px;
}

.not-edit {
  margin-bottom: 5px;

  :deep(.el-input__wrapper) {
    background-color: #fff;
    box-shadow: 0 0 0 0px var(--el-disabled-border-color) inset !important;
  }

  :deep(.el-input__wrapper:hover) {
    background-color: var(--el-fill-color-light);
  }
}
</style>
